import { Difficulty, GameMode, world } from "@minecraft/server";
import { PlayerGroup } from "@sapi-game/gamePlayer";
import { AutoStopState } from "@sapi-game/gameState/common/autoStop";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { BlockedInCombatContext } from "./context";
import {
    BlockedInCombatConfig,
    BlockedTeamColors,
    BlockedTeamData,
} from "./interface";
import { BlockedInCombatModule } from "./module";
import { BlockedLoadState } from "./states/loadState";

export class BlockedInCombat extends BlockedInCombatModule.Engine<{
    teams: [BlockedTeamColors, PlayerGroup][];
    config: BlockedInCombatConfig;
}> {
    protected override buildContext(config: {
        teams: [BlockedTeamColors, PlayerGroup][];
        config: BlockedInCombatConfig;
    }): BlockedInCombatContext {
        const teams = config.teams.map((g) =>
            this.groupBuilder.fromGroup<BlockedTeamData>(g[1], { color: g[0] })
        );

        return new BlockedInCombatContext(teams, config.config);
    }

    override onStart(): void {
        this.pushState(AutoStopState, {
            groupSet: this.context.groupSet,
            onLeave(p) {
                this.groupSet.sendMessage(`${p.name} 离开了惊天矿工团`);
            },
        });
        this.pushState(BlockedLoadState);
    }

    override onStop(): void {
        this.context.groupSet.forEach((p) => {
            p.player.setGameMode(GameMode.Adventure);
            p.clear();
            p.runCommand("effect @s clear");
            p.player.teleport({ x: 868, y: -52.0, z: 944.5 });
            p.player.setSpawnPoint();
        });
        //重置游戏规则
        world.gameRules.fallDamage = false;
        world.gameRules.pvp = false;
        world.setDifficulty(Difficulty.Peaceful);
        //杀死所有区域内生物
        this.context.map.region
            .getEntitesInRegion({ excludeTypes: [EntityTypeIds.Player] })
            .forEach((e) => e.remove());
    }
}
